package com.jfinal.weixin.pay;

import com.alibaba.fastjson.JSON;
import com.jfinal.utils.Digests;
import com.jfinal.utils.Exceptions;
import com.jfinal.utils.Xml2StringKit;
import com.jfinal.utils.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Map;

/**
 * @author LarryKoo(larrykoo@126.com)
 * @date 2016-01-15
 */
@Slf4j
public class RedPackKit {

    private final static String redPackURI = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

    /**
     * 生成红包接口签名Sign
     *
     * @param paramLinkStr
     * @param key
     * @return
     */
    public static String createRedPackSign(String paramLinkStr, String key) {
        String signTemp = paramLinkStr + "&key=" + key;
        return Digests.md5(signTemp).toUpperCase();
    }

    /**
     * 加入签名数据, 返回构建好的SendRedPackModel对象
     *
     * @param srp
     * @param key
     * @return
     */
    public static SendRedPackModel redPackSign(SendRedPackModel srp, String key) {
        Map<String, String> redPackMap = JSON.parseObject(JSON.toJSONString(srp), Map.class);

        //创建参与签名字符串
        String signStr = Xml2StringKit.parseLinkString(redPackMap);
        String sign = createRedPackSign(signStr, key);
        srp.setSign(sign);

        return srp;
    }

    /**
     * 转换RedPackModel对象为xml字符串
     *
     * @param srp
     * @return
     */
    public static String covertRedPack2Xml(SendRedPackModel srp) {
        String xml = Xml2StringKit.json2xml(JSON.toJSONString(srp));
        return "<xml>" + xml + "</xml>";
    }

    /**
     * 发送微信红包
     *
     * @param srp
     * @return
     */
    public static ReturnRedPackModel sendRedPack(SendRedPackModel srp, String certPath, String certPass) {
        ReturnRedPackModel resultRedPack = null;
        try {
            if (new File(certPath).exists()) {
                String xml = covertRedPack2Xml(srp);
                String res = HttpUtil.postSSL(redPackURI, xml, certPath, certPass);
                if (StringUtils.isNotBlank(res)) {
                    String json = Xml2StringKit.xml2json(res);
                    resultRedPack = JSON.parseObject(JSON.parseObject(json).getString("xml"), ReturnRedPackModel.class);
                } else {
                    log.debug("sendRedPack-return:{}", res);
                }
            }
        } catch (Throwable t) {
            throw Exceptions.unchecked(t);
        } finally {
            return resultRedPack;
        }


    }
}
